<!--
 * @Author: your name
 * @Date: 2021-07-11 17:37:35
 * @LastEditTime: 2021-07-11 19:25:38
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue-hr-project\src\components\UploadImg\index.vue
-->
<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar"> -->
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
// 引入一个必要的COS模块
var COS = require('cos-js-sdk-v5')
// 实例化 COS 对象
const cos = new COS({
  SecretId: 'AKIDwgAOM3SaR2MWP1LPDjywe5F8l7DbiY7Q', // 身份识别ID
  SecretKey: '4sQgfNoyqRmqd9PN4UeW7RTFkyvay6xf' // 身份秘钥
})
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: ''
    }
  },
  methods: {
    upload(data) {
      console.log(data)
      if (data.file) {
        // 执行上传操作
        cos.putObject({
          Bucket: 'baogang-1306496776', /* 存储桶 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: data.file.name, /* 文件名 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: data.file, // 上传文件对象
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData))
          }
        }, (err, data) => {
          console.log(err || data)
          // 上传成功之后
          if (data.statusCode === 200) {
            // this.imageUrl = `https:${data.Location}`
            this.$emit('input', `https:${data.Location}`)
          }
        })
      }
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
